<?php
/* 参观者相关操作控制器 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class VisitorController extends HomeController

{
    //获取列表
    public function list(Request $request)
    {
        try {
            // 分页参数
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);
            $name = $request->input('name');

            //要查询的字段
            $field = ['id', 'user_id', 'name', 'ID_type', 'ID_num', 'phone'];

            $condition = [];
            if ($name) {
                $condition[] = ['name', 'like', '%' . $name . '%'];
            }

            // 查询数据表
            $data = DB::table('visitor')->where($condition)->select($field)->orderBy('created_at', 'desc')->offset(($page - 1) * $limit)->limit($limit)->get()->toArray();
            // 统计总记录数
            $count = DB::table('visitor')->count();

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
                'count' => $count,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取公告列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取公告列表失败',
                'data' => null
            ]);
        }
    }

    

    //详情
    public function detail(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            $field = ['title', 'content', 'is_top'];
            //根据id查询详情
            $data = DB::table('visitor')->where('id', $id)->select($field)->first();

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE,'data' => $data]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取公告详情失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取公告详情失败',
                'data' => null
            ]);
        }
    }

}
